<template>
  <van-sticky>
    <van-nav-bar
        v-if="blogUser"
        :title="`${blogUser.username}的主页`"
        left-arrow
        @click-left="onClickLeft"
        @click-right="onClickRight">
      <template #right>
        <van-icon name="search" size="18"/>
      </template>
    </van-nav-bar>
  </van-sticky>

  <blog-user-intro v-if="blogUser" :blogUser="blogUser" @update-followed="updateFollowed"/>
  <van-tabs v-model:active="activeTabIndex" @change="onTabChange">
    <van-tab title="博客"/>
    <van-tab title="收藏"/>
    <van-tab title="点赞"/>
    <van-tab title="浏览"/>
  </van-tabs>
  <blog-card-list :blogList="blogList" @delete-blog="deleteBlog"/>
  <van-empty v-show="!blogList || blogList.length < 1" description="数据为空"/>
</template>

<script setup lang="ts">
import BlogCardList from "../../components/BlogCardList.vue";
import {onMounted, ref} from "vue";
import myAxios from "../../plugins/myAxios";
import {useRoute, useRouter} from "vue-router";
import BlogUserIntro from "../../components/BlogUserIntro.vue";
import { showToast } from "vant";

const route = useRoute();

const router = useRouter();

const userId = route.params.id;

// 当前选中的标签值（用于loadData）
const active = ref(-1);
// 当前选中的标签索引（用于van-tabs组件）
const activeTabIndex = ref(0);

const blogList = ref([]);

const blogUser = ref();

const updateFollowed = (newFollowed: boolean) => {
  if (blogUser.value && blogUser.value.followed) {
    blogUser.value.followed = newFollowed;
  }
};

onMounted(async () => {
  activeTabIndex.value = 0; // 确保初始标签为博客
  active.value = -1; // 对应博客标签的值
  await loadData(-1);
  console.log('初始化完成，加载博客列表');
});

const loadData = async (type) => {
  try {
    console.log('请求数据类型:', type);
    // 显示加载提示
    showToast({
      message: '加载中...',
      duration: 500,
    });
    
    // 确保userId存在
    if (!userId) {
      console.error('用户ID不存在');
      showToast('用户ID不存在');
      return;
    }
    
    console.log(`发送请求 /blog/user/list, userId=${userId}, type=${type}`);
    
    const res: any = await myAxios.post('/blog/user/list', {
      type: type,
      userId: userId,
      pageNum: 1,
      pageSize: 8,
    });
    
    if (res?.code === 0) {
      // 确保blogVOList和blogUserVO存在
      if (res.data && res.data.blogVOList) {
        blogList.value = res.data.blogVOList;
        console.log(`成功加载${res.data.blogVOList.length}条数据，类型: ${type}`);
        console.log('数据示例:', res.data.blogVOList.length > 0 ? res.data.blogVOList[0] : '无数据');
      } else {
        blogList.value = []; // 如果博客列表为空，设置为空数组
        console.warn(`获取${getTabName(type)}列表为空`);
      }
      
      if (res.data && res.data.blogUserVO) {
        blogUser.value = res.data.blogUserVO;
      }
    } else {
      console.error('获取博客列表失败:', res?.description || '未知错误');
      blogList.value = []; // 清空列表
      showToast(`获取${getTabName(type)}列表失败: ${res?.description || '未知错误'}`);
    }
  } catch (error) {
    console.error(`加载${getTabName(type)}数据出错:`, error);
    blogList.value = []; // 出错时清空列表
    showToast(`加载${getTabName(type)}列表出错，请稍后重试`);
  }
};

// 根据类型获取标签名称
const getTabName = (type) => {
  switch (type) {
    case -1: return '博客';
    case 3: return '收藏';
    case 4: return '点赞';
    case 5: return '浏览';
    default: return '博客';
  }
};

// 标签值与索引的对应关系
const tabMap = {
  0: -1, // 博客
  1: 3,  // 收藏
  2: 4,  // 点赞
  3: 5   // 浏览
};

const onTabChange = (index) => {
  console.log('Tab changed to index:', index);
  try {
    // 根据索引获取对应的值
    const typeValue = tabMap[index];
    if (typeValue !== undefined) {
      active.value = typeValue;
      loadData(typeValue);
    } else {
      showToast('未知的标签索引');
      console.error('未知的标签索引', index);
    }
  } catch (error) {
    console.error('标签切换出错:', error);
  }
};

const deleteBlog = async () => {
  loadData(active.value);
};

const onClickLeft = () => {
  router.back();
};

const onClickRight = () => {
  router.push('/search');
};

</script>

